// pages/goods_detail/index.js
import { request } from "../../request/request.js";
import regeneratorRuntime from "../../lib/runtime/runtime";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isCollected: false
  },

  // 请求获取到商品的信息数据
  goods: {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options;
    // console.log(options.goods_id);
    const {goods_id} = options;
    this.getGoodsDetail(goods_id);
  },

  // 发送请求，获取商品的信息数据
  async getGoodsDetail(goods_id) {
    let res = await request({url: "/goods/detail",data: {goods_id}});
    this.goods = res.data.message;
    // 判断商品是否被收藏过
    const colleciton = wx.getStorageSync("collection") || [];
    const isCollected = colleciton.some(v => v.goods_id === goods_id);
    this.setData({
      isCollected,
      goods_name: this.goods.goods_name,
      goods_price: this.goods.goods_price,
      goods_introduce: this.goods.goods_introduce.replace(/\.webp/g,'.jpg'),
      goods_pics: this.goods.pics
    });
  },

  // 处理点击轮播图
  handleSwiper(e) {
    const current = e.currentTarget.dataset.url;
    const urls = this.goods.pics.map(v => {return v.pics_mid});
    wx.previewImage({
      current,
      urls: urls
    });
  },

  // 处理加入购物车的点击
  handleCartAdd() {
    // 获取本地缓存的购物车信息
    let cart = wx.getStorageSync("cart") || [];
    // 查看购物车中是否有该商品的信息
    let index = cart.findIndex(v => v.goods_id === this.goods.goods_id);
    // 有则将其数量num++，后更新本地购物车缓存
    // 无则添加该商品信息，后更新本地购物车缓存
    if (index !== -1) 
    {
      cart[index].num++;
    }
    else 
    {
      this.goods.num = 1;
      this.goods.checked = true;
      cart.push(this.goods);
    }
    // 更新本地购物车缓存
    wx.setStorageSync("cart",cart);
    // 提示加入购物车成功
    wx.showToast({
      title: '加入成功！',
      icon: 'success',
      mask: true,
    });
  },

  // 点击商品收藏图标
  handleCollect() {
    const collection = wx.getStorageSync("collection") || [];
    let index = collection.findIndex(v => v.goods_id === this.goods.goods_id);
    if (index !== -1) 
    {
      collection.splice(index,1);
      wx.showToast({
        title: '取消收藏',
        icon: 'success'
      });
    }
    else 
    {
      collection.push(this.goods);
      wx.showToast({
        title: '收藏成功',
        icon: 'success'
      });
    }
    const isCollected = !this.data.isCollected;
    this.setData({isCollected});
    wx.setStorageSync("collection", collection);
  },

  // 处理立即购买
  handleNowToBuy() {
    wx.showToast({
      title: '该功能正在开发中',
      icon: 'none',
      mask: true
    });
  }
})